<?php

namespace app\index\dao;

use app\common\model\Knowledge;
use ShidianUtil\Thinkphp\Dao\DaoTrait;
use think\Collection;

/**
 * KnowledgeDao 数据访问对象
 * Class KnowledgeDao
 * @package app\index\dao
 * @method Knowledge findByPK(?int $id, $field = true)
 * @method \think\Collection selectAll(?int $page, ?int $page_size, $field = true)
 * @method Knowledge insertActive(array $params, array $allow_field = [])
 * @method Knowledge updateActive(Knowledge $model, array $params, array $allow_field = [])
 * @method Knowledge findAndUpdateActive(int $id, array $params, array $allow_field = [])
 * @method Knowledge updateActiveByClosure(\Closure $closure, array $params, array $allow_field = [])
 * @method void deleteModel(Knowledge $model)
 * @method void deleteById(int|array|\Closure $id, bool $force = false)
 * @link https://www.kancloud.cn/manual/thinkphp6_0/1037579
 * @link https://www.kancloud.cn/manual/think-orm/1257998
 * @link https://www.kancloud.cn/thinkphp/master-database-and-model/265551
 */
class KnowledgeDao
{
    use DaoTrait;

    /**
     * @var Knowledge
     */
    private $baseModel;

    /**
     * KnowledgeDao constructor.
     */
    public function __construct()
    {
        $this->baseModel = Knowledge::class;
    }

    /**
     * 知识列表
     * @param $categoryId
     * @param $isHot
     * @param $kw
     * @param $excluded
     * @param $page
     * @param $page_size
     * @return Collection
     */
    public function select($categoryId, $isHot, $kw, $excluded, $page, $page_size): Collection
    {
        $query = Knowledge::when(is_id($categoryId), fn($query) => $query->where('categoryId', $categoryId))
            ->when(is_numeric($isHot), fn($query) => $query->where('isHot', $isHot))
            ->where('checkStatus', 1)
            ->search('title', $kw);

        if (!empty($excluded)) {
            $query->whereNotIn('id', $excluded);
        }

        return $query->field(['id', 'title', 'created', 'smallPic', 'readNum', 'isHot'])
            ->append(['smallPicImgThumb'])
            ->hidden(['smallPic'])
            ->order('isHot', 'DESC')
            ->order('id', 'DESC')
            ->paging($page, $page_size)
            ->select();
    }

    /**
     * 详情
     * @param $id
     * @return Knowledge|null
     */
    public function find($id): ?Knowledge
    {
        return Knowledge::where('id', $id)
            ->append(['smallPicImg'])
            ->hidden(['smallPic'])
            ->find();
    }
}
